package com.kckj.comm.util;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 时间工具类
 * 
 *
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";
    public static String YYYY_MM_DD2 = "yyyy/MM/dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static String HH_MM_SS = "HH:mm:ss";

    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    private static String[] parsePatterns = {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss",
            "yyyy.MM.dd HH:mm", "yyyy.MM"};

    private static String nowBeginTime = " 00:00:00";

    private static String nowEndTime = " 23:59:59";


    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String dateTime2(final Date date) {
        return parseDateToStr(YYYY_MM_DD2, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) throws ParseException {
        if (str == null) {
            return null;
        }
        return parseDate(str.toString(), parsePatterns);
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoorFormat(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        String timing = null;
        if (day > 0) {
            timing += day + ":";
        }
        if (hour <= 9) {
            timing = "0" + hour;
        } else {
            timing += hour;
        }

        timing = timing + ":" + min;
        return timing;
    }

    public static String formatDate(Date time, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        if (time != null) {
            return sdf.format(time);
        }
        return "";
    }

    public static String addMillisecond(Date startTime, long millisecond) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long endTimeNum = startTime.getTime() + millisecond;
        Date endTime = new Date();
        endTime.setTime(endTimeNum);
        return sdf.format(endTime);
    }

    public static String reduceMillisecond(Date startTime, long millisecond) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long endTimeNum = startTime.getTime() - millisecond;
        Date endTime = new Date();
        endTime.setTime(endTimeNum);
        return sdf.format(endTime);
    }

    /**
     * 当前时间 0点
     */
    public static Date dateTimeNowZero() {
        return DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.dateTimeNow("yyyy-MM-dd") + DateUtils.nowBeginTime);
    }

    /**
     * 当前时间 24点
     */
    public static Date dateTimeNow24End() {
        return DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.dateTimeNow("yyyy-MM-dd") + DateUtils.nowEndTime);
    }

    /**
     * 当前时间 0点
     */
    public static String dateTimeNowZeroStr() {
        return DateUtils.dateTimeNow("yyyy-MM-dd") + DateUtils.nowBeginTime;
    }

    /**
     * 当前时间 24点
     */
    public static String dateTimeNow24EndStr() {
        return DateUtils.dateTimeNow("yyyy-MM-dd") + DateUtils.nowEndTime;
    }

//    public static void main(String[] args) {
//        Date beginDate = getWeekStart();
//        Date endDate = getWeekEnd();
//        System.out.println("beginDate==" + beginDate + ";;;;endDate==" + endDate);
//    }

    public static String getWeek() {
        return formatDate(new Date(), "E");
    }

    public static String getWeek(Date date) {
        return formatDate(date, "E");
    }

    /**
     * 功能：获取本周的开始时间
     * 示例：2013-05-13 00:00:00
     */
    public static Date getWeekStart() {// 当周开始时间
        Calendar currentDate = Calendar.getInstance();
        currentDate.setFirstDayOfWeek(Calendar.MONDAY);
        currentDate.set(Calendar.HOUR_OF_DAY, 0);
        currentDate.set(Calendar.MINUTE, 0);
        currentDate.set(Calendar.SECOND, 0);
        currentDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return (Date) currentDate.getTime();
    }

    public static String getWeekStartStr() {// 当周开始时间
        Date date = getWeekStart();
        return formatDate(date, YYYY_MM_DD_HH_MM_SS);
    }

    /**
     * 功能：获取本周的结束时间
     * 示例：2013-05-19 23:59:59
     */
    public static Date getWeekEnd() {// 当周结束时间
        Calendar currentDate = Calendar.getInstance();
        currentDate.setFirstDayOfWeek(Calendar.MONDAY);
        currentDate.set(Calendar.HOUR_OF_DAY, 23);
        currentDate.set(Calendar.MINUTE, 59);
        currentDate.set(Calendar.SECOND, 59);
        currentDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        return (Date) currentDate.getTime();
    }

    public static String getWeekEndStr() {// 当周开始时间
        Date date = getWeekEnd();
        return formatDate(date, YYYY_MM_DD_HH_MM_SS);
    }


    public static String getMonth() {
        return formatDate(new Date(), "MM");
    }

    public static String getMonth(String dateStr) {
        if (StringUtils.isEmpty(dateStr)) {
            return "";
        } else {
            Date date = parse(dateStr, "yyyy-MM-dd");
            return getMonth(date);
        }
    }

    public static String getMonth(Date date) {
        return formatDate(date, "MM");
    }

    public static Date parse(String date, String pattern) {
        SimpleDateFormat df = new SimpleDateFormat(pattern);

        try {
            return df.parse(date);
        } catch (ParseException var4) {
            var4.printStackTrace();
            return null;
        }
    }

    /**
     * 获取这个月第一天的日期 结果 yyyy-MM-dd
     *
     * @param date
     * @return
     */
    public static String getMinMonthDate(String date) {
        Calendar calendar = Calendar.getInstance();

        try {
            calendar.setTime(dateFormat.parse(date));
            calendar.set(5, calendar.getActualMinimum(5));
            return dateFormat.format(calendar.getTime());
        } catch (ParseException var3) {
            var3.printStackTrace();
            return null;
        }
    }

    /**
     * 获取这个月最后一天的日期 结果 yyyy-MM-dd
     *
     * @param date
     * @return
     */
    public static String getMaxMonthDate(String date) {
        Calendar calendar = Calendar.getInstance();

        try {
            calendar.setTime(dateFormat.parse(date));
            calendar.set(5, calendar.getActualMaximum(5));
            return dateFormat.format(calendar.getTime());
        } catch (ParseException var3) {
            var3.printStackTrace();
            return null;
        }
    }

    /**
     * 得到几天前的时间
     *  
     *
     * @param d
     * @param day
     * @return
     */
    public static Date getDateBefore(Date d, int day) {
        Calendar no = Calendar.getInstance();
        no.setTime(d);
        no.set(Calendar.DATE, no.get(Calendar.DATE) - day);
        return no.getTime();
    }

    /**
     * 得到几天前的时间 返回结果 yyyy-MM-dd
     *  
     *
     * @param d
     * @param day
     * @return
     */
    public static String getDateBeforeStr(Date d, int day) {
        Date date = getDateBefore(d, day);
        return formatDate(date, YYYY_MM_DD);
    }


    /**
     * 得到几天后的时间
     *  
     *
     * @param d
     * @param day
     * @return
     */
    public static Date getDateAfter(Date d, int day) {
        Calendar no = Calendar.getInstance();
        no.setTime(d);
        no.set(Calendar.DATE, no.get(Calendar.DATE) + day);
        return no.getTime();
    }

    /**
     * 得到几天后的时间 返回结果 yyyy-MM-dd
     *  
     *
     * @param d
     * @param day
     * @return
     */
    public static String getDateAfterStr(Date d, int day) {
        Date date = getDateAfter(d, day);
        return formatDate(date, YYYY_MM_DD);
    }


    /**
     * 获取当前时间前N分钟
     *
     * @param minute
     * @return
     */
    public static String getCurrentMinuteBefore(int minute) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.MINUTE, -minute);// N分钟之前的时间
        Date beforeD = beforeTime.getTime();
        String time = sdf.format(beforeD);
        return time;
    }

    /**
     * 获取当前时间前N分钟
     *
     * @param minute
     * @return
     */
    public static String getCurrentMinuteAfter(int minute) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.MINUTE, minute);// N分钟之后的时间
        Date beforeD = beforeTime.getTime();
        String time = sdf.format(beforeD);
        return time;
    }

    /**
     * 通过毫秒 获取 时间字符串
     *
     * @param millisecond
     * @return
     */
    public static String getDateStrByMillisecond(String millisecond, String pattern) {
        Date date = new Date();
        date.setTime(Long.valueOf(millisecond));
        if (StringUtils.isNotEmpty(pattern)) {
            pattern = YYYY_MM_DD_HH_MM_SS;
        }
        return DateUtils.parseDateToStr(pattern, date);
    }

    /**
     * 判断时分 大小 是否为次日
     *
     * @param s1
     * @param s2
     * @return
     */
    public static boolean compTime(String s1, String s2) {
        try {
            if (s1.indexOf(":") < 0 || s1.indexOf(":") < 0) {
                System.out.println("格式不正确");
            } else {
                String[] array1 = s1.split(":");
                int total1 = Integer.valueOf(array1[0]) * 3600 + Integer.valueOf(array1[1]) * 60;
                String[] array2 = s2.split(":");
                int total2 = Integer.valueOf(array2[0]) * 3600 + Integer.valueOf(array2[1]) * 60;
                return total1 - total2 > 0 ? true : false;
            }
        } catch (NumberFormatException e) {
            return true;
        }
        return false;
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoorByDay(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        return day + "";
    }

    /**
     * 取得日期：年
     *
     * @param date
     * @return
     */
    public static String getYear(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int year = c.get(Calendar.YEAR);
        return String.valueOf(year);
    }


    /**
     * 取得季度月
     *
     * @param date
     * @return
     */
    public static int getSeasonDate(Date date) {
        Date[] season = new Date[3];

        Calendar c = Calendar.getInstance();
        c.setTime(date);

        int nSeason = getSeason(date);
      /*  if (nSeason == 1) {// 第一季度
            c.set(Calendar.MONTH, Calendar.JANUARY);
            season[0] = c.getTime();
            c.set(Calendar.MONTH, Calendar.FEBRUARY);
            season[1] = c.getTime();
            c.set(Calendar.MONTH, Calendar.MARCH);
            season[2] = c.getTime();
        } else if (nSeason == 2) {// 第二季度
            c.set(Calendar.MONTH, Calendar.APRIL);
            season[0] = c.getTime();
            c.set(Calendar.MONTH, Calendar.MAY);
            season[1] = c.getTime();
            c.set(Calendar.MONTH, Calendar.JUNE);
            season[2] = c.getTime();
        } else if (nSeason == 3) {// 第三季度
            c.set(Calendar.MONTH, Calendar.JULY);
            season[0] = c.getTime();
            c.set(Calendar.MONTH, Calendar.AUGUST);
            season[1] = c.getTime();
            c.set(Calendar.MONTH, Calendar.SEPTEMBER);
            season[2] = c.getTime();
        } else if (nSeason == 4) {// 第四季度
            c.set(Calendar.MONTH, Calendar.OCTOBER);
            season[0] = c.getTime();
            c.set(Calendar.MONTH, Calendar.NOVEMBER);
            season[1] = c.getTime();
            c.set(Calendar.MONTH, Calendar.DECEMBER);
            season[2] = c.getTime();
        }*/
        return nSeason;
    }
    /**
     *
     * 1 第一季度 2 第二季度 3 第三季度 4 第四季度
     *
     * @param date
     * @return
     */
    public static int getSeason(Date date) {

        int season = 0;

        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int month = c.get(Calendar.MONTH);
        switch (month) {
            case Calendar.JANUARY:
            case Calendar.FEBRUARY:
            case Calendar.MARCH:
                season = 1;
                break;
            case Calendar.APRIL:
            case Calendar.MAY:
            case Calendar.JUNE:
                season = 2;
                break;
            case Calendar.JULY:
            case Calendar.AUGUST:
            case Calendar.SEPTEMBER:
                season = 3;
                break;
            case Calendar.OCTOBER:
            case Calendar.NOVEMBER:
            case Calendar.DECEMBER:
                season = 4;
                break;
            default:
                break;
        }
        return season;
    }

    /**
     * 描述:  获取当月的第一天
     * String time = "202001";
     * @return
     * @Param time
     * @author 代文杰
     * @version V1.0
     * @Date
     */
    public static String getMonthStart(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        try {
            Date date = sdf.parse(time);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            int index = calendar.get(Calendar.DAY_OF_MONTH);
            calendar.add(Calendar.DATE, (1 - index));
            String format1 = sdf.format(calendar.getTime());
            Date parse1 = sdf.parse(format1);
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            return sdf1.format(parse1) + " 00:00:00";
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 描述:  获取当月的最后一天
     * String time = "202001";
     * @return
     * @Param time
     * @author 代文杰
     * @version V1.0
     * @Date
     */
    public static String getLastDayOfMonth(String time) {
        int year = Integer.parseInt(time.substring(0,4));
        int month = Integer.parseInt(time.substring(4));
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR,year);
        cal.set(Calendar.MONTH, month-1);
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime()) + " 23:59:59";
    }

    /**
     * 描述:  根据 年月 查询：月初，月末，季度初，季度末，年度初，年度末的时间
     *  String time = "202001";
     * @return
     * @Param time
     * @author 代文杰
     * @version V1.0
     * @Date
     */
    public static Map<String, Date> getAllTime(String time) throws ParseException {
        Map<String, Date> map = new HashMap<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
        Date parse = simpleDateFormat.parse(time);
        int season = DateUtils.getSeason(parse);
        String yearStart = DateUtils.getMonthStart(time.substring(0,4) + "01");
        String yearEnd = DateUtils.getLastDayOfMonth(time.substring(0,4) + "12");
        String monthStart = getMonthStart(time);
        String monthEnd = getLastDayOfMonth(time);
        String quarterlyStart = DateUtils.getMonthStart(time.substring(0,4) + (season * 3 - 2));
        String quarterlyEnd = DateUtils.getLastDayOfMonth(time.substring(0,4) + season * 3);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("yearStart",sdf.parse(yearStart));
        map.put("yearEnd",sdf.parse(yearEnd));
        map.put("monthStart",sdf.parse(monthStart));
        map.put("monthEnd",sdf.parse(monthEnd));
        map.put("quarterlyStart",sdf.parse(quarterlyStart));
        map.put("quarterlyEnd",sdf.parse(quarterlyEnd));
        return map;
    }

    /**
     * 时间戳转换为日期
     * @param str_num
     * @return
     */
    public static String timestamp2Date(String str_num ) {
        SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        if (str_num.length() == 13) {
            String date = sdf.format(new Date(Long.parseLong(str_num)));
            return date;
        } else {
            String date = sdf.format(new Date(Integer.parseInt(str_num) * 1000L));
            return date;
        }
    }


    public static void main(String[] args) throws ParseException {
        Date date = dateTime(YYYY_MM_DD_HH_MM_SS, "2020-12-18 14:10:47");
        System.out.println(date);
        Date date1 = new Date();
        System.out.println(date1);
    }
}